<template>
  <el-tabs  type="border-card">
    <el-tab-pane >
      <span slot="label"><i class="el-icon-date"></i> 商品基本信息</span>

      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="商品分类" >
          <el-select v-model="dataForm.goods.category1Id" placeholder="一级分类">
            <el-option
              v-for="item in categorys1"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.goods.category2Id" placeholder="二级分类">
            <el-option
              v-for="item in categorys2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.goods.category3Id" placeholder="三级分类">
            <el-option
              v-for="item in categorys3"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          模板ID:{{dataForm.goods.typeTemplateId}}
        </el-form-item>

      </el-form>
      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="商品名称" style="width:70%">
          <el-input v-model="dataForm.goods.goodsName" placeholder="商品名称"></el-input>
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="品牌" style="width: 70%">
          <el-select v-model="dataForm.goods.brandId" placeholder="品牌" style="width:100%" clearable>
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form ref="form" :model="dataForm" label-width="180px">
          <el-form-item label="副标题" style="width:70%">
            <el-input v-model="dataForm.goods.caption" placeholder="副标题"></el-input>
          </el-form-item>
        </el-form>
        <el-form ref="form" :model="dataForm" label-width="180px">
          <el-form-item label="价格" style="width:70%">
            <el-input v-model="dataForm.goods.price" placeholder="价格"></el-input>
          </el-form-item>
        </el-form>
        <el-form ref="form" :model="dataForm" label-width="180px">
          <el-form-item label="商品介绍" style="width:70%">
            <el-input type="textarea" v-model="dataForm.goodsDesc.introduction" placeholder="商品介绍"></el-input>
          </el-form-item>
        </el-form>
        <el-form ref="form" :model="dataForm" label-width="180px">
          <el-form-item label="包装列表" style="width:70%">
            <el-input type="textarea" v-model="dataForm.goodsDesc.packageList " placeholder="包装列表"></el-input>
          </el-form-item>
        </el-form>
        <el-form ref="form" :model="dataForm" label-width="180px">
          <el-form-item label="售后服务" style="width:70%">
            <el-input type="textarea" v-model="dataForm.goodsDesc.saleService" placeholder="售后服务"></el-input>
          </el-form-item>
        </el-form>
      </el-form>
    </el-tab-pane>
    <el-tab-pane>
      <span slot="label"><i class="el-icon-date"></i> 商品图片</span>
      <el-button type="primary" plain size="small" @click="newUpload">新建</el-button>
      <el-table
        :data="dataForm.goodsDesc.itemImages"
        style="width: 100%;">
        <el-table-column
          prop="color"
          header-align="center"
          align="center"
          label="颜色">
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.url" width="100px" height="50px">
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="dataForm.goodsDesc.itemImages.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="图片上传" :visible.sync="dialogFormVisible">
        <el-form :model="imageEntity">
          <el-form-item label="图片颜色" label-width="100px">
            <el-input v-model="imageEntity.color" ></el-input>
          </el-form-item>
          <el-form-item label="商品图片" label-width="100px">
            <!--文件上传组件-->
            <!--:http-request="uploadFile" 此代码代表自定义文件上传-->
            <el-upload
              action=""
              class="upload-demo"
              :file-list="fileList"
              :http-request="uploadFile"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="closeUpload">确 定</el-button>
        </div>
      </el-dialog>
    </el-tab-pane>
    <el-tab-pane >
      <span slot="label"><i class="el-icon-date"></i> 扩展属性</span>
      {{dataForm}}--
      <el-table
        :data="dataForm.goodsDesc.customAttributeItems"
        style="width: 100%;">
        <el-table-column
          header-align="center"
          width="200px"
          align="center">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          width="600px"
          align="center">
          <template slot-scope="scope">
           <el-input v-model="scope.row.value" placeholder="属性值"/>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane>
      <span slot="label"><i class="el-icon-date"></i> 规格</span>
      <el-table
        :data="specificationItems"
        style="width: 100%;">
        <el-table-column width="200px" align="center">
          <template slot-scope="scope" >
            <span >{{scope.row.text}}</span>
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-checkbox-group v-model="optionList[scope.$index]" size="mini" >
              <el-checkbox :label="option.optionName" border v-for="option in scope.row.options" :key="option.id" @change="getOptionList"></el-checkbox>
            </el-checkbox-group>
            <!--<el-checkbox-group  size="mini" v-model="optionList[scope.$index]"-->
            <!--                    @change="getOptionList">-->
            <!--  <el-checkbox border v-for="option in scope.row.options" :label="option.optionName" :key="option.id" />-->
            <!--</el-checkbox-group>-->
          </template>
        </el-table-column>
      </el-table>

      <el-table
        :data="dataForm.items"
        style="width: 100%;">
        <el-table-column width="200px" align="center"
                         :key="key" :label="spec.attributeName"
                         v-for="(spec,key) in dataForm.goodsDesc.specificationItems">
          <template slot-scope="scope">
            {{scope.row.spec[spec.attributeName]}}
          </template>
        </el-table-column>

        <!--2.2 处理价格-->
        <el-table-column  label="价格"  align="center" >
          <template slot-scope="scope">
            <el-input v-model="scope.row.price"/>
          </template>
        </el-table-column>
        <!--2.3 处理数量-->
        <el-table-column  label="数量"  align="center" >
          <template slot-scope="scope">
            <el-input v-model="scope.row.num"/>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-button type="success" size="small" plain @click="save">保存</el-button>
    <el-button type="warning" size="small" plain>返回列表</el-button>
  </el-tabs>
</template>

<script>

  export default {
    data () {
      return {
        dataForm:{goods:{typeTemplateId:''},goodsDesc:{itemImages:[],customAttributeItems:[],specificationItems:[]},items:[]},
        categorys1:[],    //一级分类
        categorys2:[],    //二级分类
        categorys3:[],    //三级分类
        brandList:[],     //某个模板的品牌列表
        dialogFormVisible:false,
        imageEntity:{},      //每次上传的图片
        fileList:[],      //存放文件列表的数组
        specificationItems:[],   //所有的规格及规格选项列表
        optionList:[],
        specNames:[],            //所有规格名称
      }

    },
    created() {
      //1. 查询一级分类
      this.findCategorys1();
      //2. 根据修改页面传入的id值得到商品对象
      this.findGoodsById();
    },
    watch:{       //观察属性值的改变
      //1. 监听一级分类的变化
      category1Idnew(newId,oldId){
        console.log('新值：',newId,',旧值：' ,oldId);
        //1. 根据当前选择的新的id值得到其下的所有的二级分类列表
        if(newId){
          this.$http({
            url: this.$http.adornUrl(`/shop/itemcat/findParentById/${newId}`),
            method: 'get'
          }).then(({data}) => {
            if (data && data.code === 0) {
              console.log("data(二级分类):",data);
              this.categorys2 = data.list;
            } else {
              this.dataList = []
            }
            this.dataListLoading = false
          })
        }

      },
      //2. 监听二级分类的值的变化
      category2Idnew(newId,oldId){
        //1. 根据当前选择的新的id值得到其下的所有的二级分类列表
        if(newId)
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findParentById/${newId}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data(三级分类):",data);
            this.categorys3 = data.list;
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      //3. 监听三级分类的值的变化
      category3Idnew(newId,oldId){
        //1. 根据当前选择的新的id值得到其下的所有的三级分类列表
        if(newId)
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/info/${newId}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data(三级分类对象):",data);
            this.dataForm.goods.typeTemplateId = data.itemCat.typeId;
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      //4. 监听模板的值的变化，会导致如下功能的改变,完成以下事情
      //① 品牌列表的改变
      //② 模板表的扩展属性
      //③ 模板表的规格并且将相应规格的选项列表也添加在规格列表中
      typeTempalteIdnew(newId,oldId){
        //1. 根据当前选择的新的id值得到其下的所有的三级分类列表
        console.log("-----typeTempalteIdnew")
        if(newId)
        this.$http({
          url: this.$http.adornUrl(`/shop/typetemplate/info/${newId}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data(模板对象):",data);
            //1.1 得到模板的品牌列表
            this.brandList = JSON.parse(data.typeTemplate.brandIds);
            //1.2 得到模板的扩展属性
            if(!this.$route.query.id){   //代表没有查询参数就作此操作
              this.dataForm.goodsDesc.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems);
            }

            //1.3 得到规格及规格选项列表
            this.$http({
              url:this.$http.adornUrl(`/shop/specification/findSpecList/${newId}`),
              method:'get'
            }).then(({data})=>{
              console.log("data--->spec:",data.list);
              //1.4 得到所有规格及规格选项列表
              this.specificationItems = data.list;
              //1.5 为规格选项列表赋值(这里一定要在修改商品id不存在时【即添加商品时】，这样设置optionList的值)
              if(!this.$route.query.id){
                this.optionList = [];
                data.list.forEach(d=>{
                  this.specNames.push(d.text);
                  this.optionList.push([]);
                })
              }
                data.list.forEach(d=>{
                  this.specNames.push(d.text);
                })
            })
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
    },
    computed:{    //自动计算属性值变化
      //1. 计算一级分类变量category1Idnew的值的变化
      category1Idnew(){    //this.dataForm.goods.category1Id属性值变化，会导致category1Idnew属性的变化
        return this.dataForm.goods.category1Id;
      },
      //2. 计算二级分类变量category2Idnew的值的变化
      category2Idnew(){    //this.dataForm.goods.category2Id属性值变化，会导致category2Idnew属性的变化
        return this.dataForm.goods.category2Id;
      },
      //3. 计算三级分类变量category3Idnew的值的变化
      category3Idnew(){    //this.dataForm.goods.category3Id属性值变化，会导致category3Idnew属性的变化
        return this.dataForm.goods.category3Id;
      },
      //4. 当模板id的值发生变化时，会导致typeTempalteIdnew变量的改变
      typeTempalteIdnew(){
        return this.dataForm.goods.typeTemplateId;
      },
    },
    methods:{
      //0. 点击某个规格选项复选框时触发
      getOptionList(){
        console.log("optionList:",this.optionList);
        let specList = [];
        if(!this.$route.query.id){

        }
        //0.1 为规格选项设置值
        for(let i = 0;i < this.optionList.length; i++){
          let option = this.optionList[i];
          specList.push({attributeName:this.specNames[i],attributeValue:option});
        }
        this.dataForm.goodsDesc.specificationItems = specList;

        console.log("-------------------->",this.specificationItems);
        //0.2 处理特殊情况：当规格选项一个也没有时就从dataForm.goodsDesc.specificationItems中删除它
        this.dataForm.goodsDesc.specificationItems = this.dataForm.goodsDesc.specificationItems.filter(f=>{
          return f.attributeValue.length > 0;
        })

        //0.3 根据用户选择规格生成规格sku商品列表
        this.createItemList();
      },
      //根据规格生成sku商品列表
      createItemList(){
          //1. 定义默认的sku商品列表
          this.dataForm.items = [{spec:{},price:0,num:9999,status:'0',isDefault:'0'}];
          //2. 得到用户选择的规格列表
          let items = this.dataForm.goodsDesc.specificationItems;
        console.log("items::::",items);
          //3. 遍历规格列表，根据列表动态生成sku列表
          if(items && items.length > 0){
            items.forEach(item=>{
              this.dataForm.items = this.createColumn(this.dataForm.items ,item.attributeName,item.attributeValue);
            })
          }

      },
      createColumn(items,specName,specValue){
        //1. 定义生成的新的sku列表数组
        let skuList = [];
        //2. 遍历传入的items，动态为sku商品列表赋值
        items.forEach(item=>{
          specValue.forEach(value=>{
              //2.1 根据旧行克隆出新行
              let newRow = JSON.parse(JSON.stringify(item));
              //2.2 为新行赋值
              newRow.spec[specName] = value;
              //2.3 将新行添加到数组中
              skuList.push(newRow);
          })
        })
        //3. 返回新的数组
        return skuList;
      },
      //1. 查询一级分类
      findCategorys1(){
        console.log("findCategorys1...")
        this.$http({
          url: this.$http.adornUrl('/shop/itemcat/findItemCat1'),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            //console.log("data:",data);
            this.categorys1 = data.list;
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      //2. 处理上传请求
      uploadFile(v){
        //2.1 组织上传的数据
        let form = new FormData();
        form.append("file",v.file);   //添加我们上传的文件对象
        //2.2 清空列表
        this.fileList = [];
        //2.3 开始文件上传
        this.$http({
          url: this.$http.adornUrl(`/shop/upload`),
          method: 'post',
          headers:{'Content-Type':'multipart/form-data'},
          data:form
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data:",data);
            this.fileList.push({name:v.raw,url:data.url})
            this.imageEntity.url = data.url;
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      //关闭文件上传
      closeUpload(){
        //1. 关闭上传对话框
        this.dialogFormVisible = false;
        //2. 为dataForm.goodsDesc.itemImages数组赋值
        this.dataForm.goodsDesc.itemImages.push(this.imageEntity);
      },
      //新的上传
      newUpload(){
        this.dialogFormVisible=true;
        this.imageEntity={}
        this.fileList = [];   //清空上传的文件列表
      },
      //保存
      save(){
        let id = this.$route.query.id;
        //1. 将需要添加的数据转换为json串
        this.dataForm.goodsDesc.specificationItems = JSON.stringify(this.dataForm.goodsDesc.specificationItems)
        this.dataForm.goodsDesc.itemImages = JSON.stringify(this.dataForm.goodsDesc.itemImages);
        this.dataForm.goodsDesc.customAttributeItems = JSON.stringify(this.dataForm.goodsDesc.customAttributeItems)
        //2. 转换this.dataForm.items中的每一个spec对象为字会串
        this.dataForm.items.forEach(item=>{
          item.spec = JSON.stringify(item.spec);
        })
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/${id?'update':'save'}`),
          method: `${id?'put':'post'}`,
          data:this.dataForm
        }).then(({data}) => {
          if (data && data.code === 0) {
            //1. 添加成功后将所有数据恢复成默认值
            // this.dataForm.goods = {};
            // this.dataForm.goodsDesc = {customAttributeItems: [],specificationItems: [],itemImages: []};
            // this.dataForm.items = [];
            this.dataForm={goods:{typeTemplateId:''},goodsDesc:{itemImages:[],customAttributeItems:[],specificationItems:[]},items:[]},
            this.specificationItems = []
            this.fileList = []
            this.optionList=[];   //选择的规格选项列表
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      //根据id查询商品
      findGoodsById(){
        //1. 得到修改页面传入的id参数
        let id = this.$route.query.id;
        console.log("id:",id);
        //2. 根据传入的商品id，从后台查询出spu商品、spu商品描述、sku商品列表
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/findGoodsById/${id}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("findGoodsById:",data);
            this.dataForm = data.goods;
            this.dataForm.goods.brandId = parseInt(data.goods.goods.brandId);   //要将原来的字符串转换为整数
            //将json串转换为json对象(一定要在监听模板id时，判断是否有查询参数id，如果没有才执行从模板表得到自定义扩展属性)
            this.dataForm.goodsDesc.customAttributeItems = JSON.parse(data.goods.goodsDesc.customAttributeItems);
            this.dataForm.goodsDesc.itemImages = JSON.parse(data.goods.goodsDesc.itemImages);
            this.dataForm.goodsDesc.specificationItems = JSON.parse(data.goods.goodsDesc.specificationItems);
            this.dataForm.items.forEach(item=>{
              item.spec = JSON.parse(item.spec);
            })
            //为this.optionList赋值，就会自动选中
            let items = this.dataForm.goodsDesc.specificationItems
            this.optionList=[]
            for(let i = 0;i < items.length;i++){
              this.optionList[i]=items[i].attributeValue;
            }
            console.log("aaaa--->",this.optionList);
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      }
    }
  }
</script>
